//
//  NewsViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/10.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "NewsViewController.h"
#import "SDCycleScrollView.h"
#import "NewsTableViewCell.h"
#import "GoodsModel.h"
#import "WenZhangDViewController.h"

@interface NewsViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SDCycleScrollView *cycleScrollView; // 轮播图
@property (nonatomic, strong) NSMutableArray *netImages; // 网络图片数组
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, strong) UITextField *searchTF;

@end

@implementation NewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorWhite;
    [self loadBaseTitleLable:@"资讯"];
    [self.view addSubview:self.tableView];
    
    self.currentPage = 1;
    self.pageSize = 20;
    // 请求数据
    [self getGoodsListData];
    [self getBannerData];
}
#pragma mark - 新闻列表
- (void)getGoodsListData
{
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/content/content.ashx?action=list&companyid=%@&channelid=104&pagesize=%@&pageindex=1&keyword=%@",kServerURL,companyId,[NSString stringWithFormat:@"%ld",(long)self.pageSize],@""] parameters:nil success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:self.view];
        self.dataArray = [NSMutableArray array];
        self.currentPage = 1;
        if ([responseObject[@"status"] intValue] == 1) {
            self.dataArray = [GoodsModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        }
        NSInteger i = [responseObject[@"count"] intValue]/self.pageSize;
        NSInteger j = [responseObject[@"count"] intValue]%self.pageSize;
        NSInteger n = 0;
        if (j > 0) {
            n = i+1;
        } else {
            n = i;
        }
        if (n<2) {
            self.tableView.mj_footer.hidden = YES;
        } else {
            self.tableView.mj_footer.hidden = NO;
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)getGoodsListDataMore
{
    self.currentPage++;
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/content/content.ashx?action=list&companyid=%@&channelid=104&pagesize=%@&pageindex=%@&keyword=%@",kServerURL,companyId,[NSString stringWithFormat:@"%ld",(long)self.pageSize],[NSString stringWithFormat:@"%ld",(long)self.currentPage],@""] parameters:nil success:^(id responseObject) {
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD hideHUDForView:self.view];
        if ([responseObject[@"status"] intValue] == 1) {
            
            NSInteger i = [responseObject[@"count"] intValue]/self.pageSize;
            NSInteger j = [responseObject[@"count"] intValue]%self.pageSize;
            NSInteger n = 0;
            if (j > 0) {
                n = i+1;
            } else {
                n = i;
            }
            if (self.currentPage > n) {
                self.currentPage--;
                self.tableView.mj_footer.hidden = YES;
            } else {
                self.tableView.mj_footer.hidden = NO;
                self.dataArray = (NSMutableArray *)[self.dataArray arrayByAddingObjectsFromArray:[GoodsModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]]];
                [self.tableView reloadData];
            }
        } else {
            self.currentPage--;
            self.tableView.mj_footer.hidden = YES;
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_footer endRefreshing];
    }];
}
#pragma mark - 获取轮播图
- (void)getBannerData
{
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/common/common.ashx?action=fragment&companyid=%@&label=sjsybanner",kServerURL,companyId] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        self.netImages = [NSMutableArray array];
        if ([responseObject[@"status"] intValue] == 1) {
            NSArray *array = responseObject[@"fragmentPictureList"];
            for (NSDictionary *dic in array) {
                [self.netImages addObject:[NSString stringWithFormat:@"http:%@",dic[@"fragmentPicture"]]];
            }
        }
        NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        
    }];
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsTableViewCell *cell = [[NewsTableViewCell alloc] init];
    if (_dataArray.count != 0) {
        GoodsModel *model = _dataArray[indexPath.row];
        if (model.images.length != 0) {
            [cell.goodsImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http:%@",model.images]]];
        } else {
            [cell.goodsImg mas_updateConstraints:^(MASConstraintMaker *make) {
                make.size.mas_offset(CGSizeMake(rateHeight(0), rateHeight(190)));
            }];
            [cell.titleLB mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_lessThanOrEqualTo(@(rateWidth(600)));
            }];
            [cell.describeLB mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_lessThanOrEqualTo(@(rateWidth(600)));
            }];
            
        }
        
        cell.titleLB.text = [NSString stringWithFormat:@"%@",model.title];
        cell.describeLB.text = model.Intro;
        [cell.commentBtn setTitle:[NSString stringWithFormat:@"  %@",model.hits] forState:(UIControlStateNormal)];
    }
    cell.selectionStyle = NO;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return rateHeight(280);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return rateHeight(360);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    // 轮播图
    if (_netImages.count != 0) {
        [bgV addSubview:self.cycleScrollView];
    }
    
    return bgV;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.dataArray.count != 0) {
        GoodsModel *model = _dataArray[indexPath.row];
        WenZhangDViewController *wenZhangDVC = [[WenZhangDViewController alloc] init];
        wenZhangDVC.Aid = model.id;
        wenZhangDVC.imgUrl = [NSString stringWithFormat:@"https:%@",model.images];
        wenZhangDVC.titleStr = model.title;
        [self.navigationController pushViewController:wenZhangDVC animated:YES];
    }
}
#pragma mark - 轮播图
- (SDCycleScrollView *)cycleScrollView
{
    if (!_cycleScrollView) {
        // 轮播图
        _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, rateHeight(360)) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
        _cycleScrollView.delegate = self;
        _cycleScrollView.showPageControl = YES;
        //        _cycleScrollView.pageDotColor = UIColorWithRGB(128, 130, 132);
        //        _cycleScrollView.currentPageDotColor = UIColorWithRGB(173, 36, 36);
        
        _cycleScrollView.pageDotImage = UIImageNamed(@"segmentGray");
        _cycleScrollView.pageControlDotSize = CGSizeMake(rateWidth(15), rateWidth(15));
        _cycleScrollView.currentPageDotImage = UIImageNamed(@"segmentRed");
        
        // 模拟延迟加载
        __weak typeof(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            weakSelf.cycleScrollView.imageURLStringsGroup = _netImages;
        });
        // 清除缓存
        [self.cycleScrollView clearCache];
    }
    return _cycleScrollView;
}
#pragma mark - 轮播图点击
#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", index);
    
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, kScreenHeight-SafeAreaTopHeight) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = tableViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        WeakSelf
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf getGoodsListData];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [weakSelf getGoodsListDataMore];
        }];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
